<template>
  <div class="container">
    <div class='fundProperty'>
      <el-row :gutter="20">
        <el-col :span="4">
          <el-card>
            <div slot="header" class="clearfix">
              <el-input v-model="filterText" placeholder="输入关键字进行过滤"></el-input>
            </div>
            <div class="card-body">
              <el-tree ref="tree" :props="defaultProps" :data="treedata" :highlight-current="true" node-key="id" :default-expand-all="true"
                :filter-node-method="filterNode2" @node-click="getNodeData"></el-tree>
            </div>
          </el-card>
        </el-col>
        <el-col :span="20">
          <el-row :gutter="6" style="margin-bottom: 10px">
            <el-col :span="24">
              <el-card>
                <div style="margin-top: 20px">
                  <el-form class="filter-container" label-position="left" label-width="120px">
                    <el-row :gutter="24">
                      <el-col :span="8">
                        <el-form-item label="基金代码" style="margin-bottom: 0 !important">
                          <el-select v-model="listQuery.code" value-key="tag_code" clearable filterable remote reserve-keyword :loading="loading" :remote-method="remoteMethodcode" class="filter-item" placeholder="输入关键词" >
                            <el-option v-for="item in fundcodeOptions" :key="item.tag_code" :label="item.name+(item.code)" :value="item.code" >
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="基金简称" style="margin-bottom: 0 !important">
                          <el-select v-model="listQuery.name" value-key="tag_code" clearable filterable remote reserve-keyword :loading="loading" :remote-method="remoteMethodname" class="filter-item" placeholder="输入关键词" >
                            <el-option v-for="item in fundnameOptions" :key="item.tag_code" :label="item.name+(item.code)" :value="item.name" >
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="基金主题" style="margin-bottom: 0 !important">
                          <el-select v-model="listQuery.theme" value-key="tag_code" clearable filterable remote reserve-keyword :loading="loading" :remote-method="remoteMethodtheme" class="filter-item" placeholder="输入关键词" >
                            <el-option v-for="item in fundthemeOptions" :key="item.tag_code" :label="item.name+(item.code)" :value="item.name" >
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="24">
                      <el-col :span="8">
                        <el-form-item label="自定义基金主题" style="margin-bottom: 0 !important">
                          <el-select v-model="listQuery.themeCusRelate" value-key="tag_code" clearable filterable remote reserve-keyword :loading="loading" :remote-method="remoteMethodCusTheme" class="filter-item" placeholder="输入关键词" >
                            <el-option v-for="item in fundCusThemeOptions" :key="item.tag_code" :label="item.name+(item.code)" :value="item.name" >
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="自定义基金行业" style="margin-bottom: 0 !important">
                          <el-select v-model="listQuery.indusCusRelate" value-key="tag_code" clearable filterable remote reserve-keyword :loading="loading" :remote-method="remoteMethodCusIndustry" class="filter-item" placeholder="输入关键词" >
                            <el-option v-for="item in fundCustIndustryOptions" :key="item.tag_code" :label="item.name+(item.code)" :value="item.name" >
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="近似词" style="margin-bottom: 0 !important">
                          <el-input @keyup.enter.native="getList" class="filter-item" placeholder="输入关键词" v-model.trim="listQuery.similarWord"></el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="24">
                      <el-col :span="8">
                        <el-form-item label="状态" style="margin-bottom: 0 !important">
                          <el-select clearable v-model="listQuery.state" placeholder="请选择">
                            <el-option value label="全部"></el-option>
                            <el-option :value="1" label="启用"></el-option>
                            <el-option :value="0" label="停用"></el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row style="float: right">
                      <el-col :span="8"></el-col>
                      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getList">查询</el-button>
                      <el-button class="filter-item el-icon-refresh" style="margin-left: 10px" @click="resetSearch" type="primary">重置</el-button>
                    </el-row>
                  </el-form>
                </div>
              </el-card>
            </el-col>
          </el-row>
          <el-row :gutter="16">
            <el-col :span="24">
              <el-card>
                <div slot="header"></div>
                <div>
                  <div style="margin-bottom: 12px">
                    <el-button style="margin-right: 10px" @click="handleAdd" type="primary" disabled>新增</el-button>
                    <el-button style="margin-right: 10px" @click="handleStart" type="primary">启用</el-button>
                    <el-button style="margin-right: 10px" @click="handleStop" type="primary">停用</el-button>
                    <el-button  style="margin-right: 10px" @click="alldelete" type="primary">批量删除</el-button>
                    <a :href="downloadInfo.url" :download="downloadInfo.name">
                      <el-button type="warning" icon="el-icon-download">下载Excel模板</el-button>
                    </a>
                    <el-button :loading="true" v-if="!!uploadFileInfo.loading" type="warning">上传中</el-button>
                    <el-upload ref="uploadButton" :action="uploadAction" accept=".xlsx, .xls" :headers="{
                        Authorization: 'Bearer ' + $store.getters.token,
                      }" style="display: inline" :on-success="startParse" :before-upload="beforeUpload">
                      <el-button v-if="!uploadFileInfo.loading" type="success" icon="el-icon-upload">上传Excel</el-button>
                    </el-upload>
                  </div>
                  <el-table stripe :data="tableData" v-loading="listLoading" element-loading-text="加载中..." border fit highlight-current-row
                    @selection-change="handleSelectionChange" style="width: 100%">
                    <el-table-column align="center" type="selection" width="55"></el-table-column>
                    <el-table-column align="center" label="标签代码">
                      <template slot-scope="scope">
                        <span>{{ scope.row.tagCode }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column align="center" label="基金代码">
                      <template slot-scope="scope">
                        <span>{{ scope.row.code }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column align="center" label="基金简称">
                      <template slot-scope="scope">
                        <el-button class="preview-button" type="text" @click="handleDet(scope.row)">{{scope.row.name}}</el-button>
                      </template>
                    </el-table-column>
                    <el-table-column align="center" label="基金主题" show-overflow-tooltip width="200">
                      <template slot-scope="scope">
                        <span :key="item.id" v-for="item in scope.row.themeRelate">{{ item.name+(item.ratio?"("+item.ratio+"%),":'') }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column align="center" label="自定义基金主题" show-overflow-tooltip width="200">
                      <template slot-scope="scope">
                        <span :key="item.id" v-for="item in scope.row.themeCusRelate">{{ item.name+(item.ratio?"("+item.ratio+"%) , ":' , ') }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column align="center" label="自定义基金行业" show-overflow-tooltip width="200">
                      <template slot-scope="scope">
                        <span :key="item.id" v-for="item in scope.row.indusCusRelate">{{ item.name+(item.ratio?"("+item.ratio+"%) , ":' , ') }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column align="center" label="近似词" show-overflow-tooltip>
                      <template slot-scope="scope">
                        <div v-if="scope.row.simWords.length>1">
                          <span v-for="k in scope.row.simWords" :key="k">{{k+','}}</span>
                        </div>
                        <div v-if="scope.row.simWords.length===1">
                          <span v-for="k in scope.row.simWords" :key="k">{{k}}</span>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column align="center" label="状态">
                      <template slot-scope="scope">
                        <span>{{ formatStatus(scope.row.state) }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column align="center" label="创建人">
                      <template slot-scope="scope">
                        <span>{{ scope.row.creater }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column align="center" label="更新人">
                      <template slot-scope="scope">
                        <span>{{ scope.row.updater }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column align="center" label="创建时间">
                      <template slot-scope="scope">
                        <span>{{ scope.row.createTime }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column align="center" label="更新时间">
                      <template slot-scope="scope">
                        <span>{{ scope.row.updateTime }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column align="center" :label="$t('table.actions')" width="150" class-name="small-padding fixed-width">
                      <template slot-scope="scope">
                        <el-tooltip content="编辑" placement="top">
                          <el-button :loading="(scope.row.editLoading = false)" class="button-icon el-icon-edit" type="primary" size="mini"
                            @click="handleShowEditor(scope.row)"></el-button>
                        </el-tooltip>
                        <el-tooltip content="删除" placement="top">
                          <el-button :loading="(scope.row.editLoading = false)" class="button-icon el-icon-delete" type="primary" size="mini"
                            @click="handleTableDelete(scope.row)"></el-button>
                        </el-tooltip>
                      </template>
                    </el-table-column>
                  </el-table>
                  <div class="pagination-container">
                    <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNum"
                      :page-sizes="[10, 20, 30, 50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
                    </el-pagination>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </div>
    <el-dialog :title="textMap[tabledialogStatus]" :visible.sync="dialogFormVisible" width="50%" append-to-body :close-on-click-modal="false">
      <el-form :rules="rules" ref="dataForm" :model="dataForm" label-position="left" label-width="130px" style="margin: 24px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="标签代码" prop="newsPlateCodes1">
              <el-input v-model="dataForm.tagCode" disabled type="text" placeholder="系统自动生成"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="基金代码" prop="code">
              <el-input v-model="dataForm.code" type="text" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="基金简称" prop="name">
          <el-input v-model="dataForm.name" type="text" placeholder="请输入"></el-input>
        </el-form-item>
         <el-form-item label="基金主题" >
           <el-tag :key="tag.id" v-for="tag in dataForm.themeRelate" >
             {{tag.name+'('+tag.ratio+'%)'}}
           </el-tag>
        </el-form-item>
        <el-form-item label="基金行业">
          <el-tag :key="tag.id" v-for="tag in dataForm.indusRelate"   >
            {{tag.name+'('+(tag.level===1?'一级':"二级")+','+tag.ratio+'%)'}}
          </el-tag>
        </el-form-item>
        <el-form-item label="自定义基金主题">
          <el-tag :key="index+tag[0]" closable v-for="(tag,index) in dataForm.customizeTheme" @close="handleThemeClose(tag)">
            {{tag[1]}}
          </el-tag>
          <el-button  class="button-new-tag" size="small" @click="showTreeDiag('3')">+</el-button>
        </el-form-item>
        <el-form-item label="自定义基金行业 ">
          <el-tag :key="index" closable v-for="(tag,index) in dataForm.customizeFirstLevs" @close="handleIndustryClose(tag)">
            {{tag[1]}}
          </el-tag>
          <el-button  class="button-new-tag" size="small" @click="showTreeDiag('1')">+</el-button>
        </el-form-item>
        <el-form-item label="近似词" prop="dbHost">
           <el-tag :key="tag" v-for="tag in dataForm.s_words" closable :disable-transitions="false" @close="handleClose1(tag)">
            {{tag}}
          </el-tag>
          <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm">
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+</el-button>
        </el-form-item>
        <el-form-item label="状态" prop="dbHost">
          <el-switch v-model="dataForm.state" active-color="#13ce66" :active-value="1" :inactive-value="0" inactive-color="#ff4949"></el-switch>
        </el-form-item>
        <el-form-item label="股票标签" prop="dbHost">
          <el-select v-model="dataForm.stockRelate" filterable remote reserve-keyword :remote-method="remoteMethod" :loading="loading" multiple placeholder="请选择" >
            <el-option v-for="item in options" :key="item.tagCode" :label="item.name+'('+item.code+')'" :value="item.tagCode" >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closedig">
          {{
          $t('table.cancel')
          }}
        </el-button>
        <el-button v-if="tabledialogStatus == 'create'" type="primary" @click="createData">{{ $t('table.confirm') }}</el-button>
        <el-button v-else type="primary" @click="updateData">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="detailstitle" :visible.sync="dialogdetails" :fullscreen='true' :close-on-click-modal="false">
      <labelDetails :tagDetails='tagDetails' :tagType='tagType'></labelDetails>
    </el-dialog>
    <el-dialog :title="dialogTitle" width="200px" custom-class="dialog-tree" :lock-scroll="true" :visible.sync="showlevTreeFlag" :close-on-click-model='false' :modal="false" >
    <el-input
      placeholder="输入关键字进行过滤"
      v-model="filterlevData">
    </el-input>
    <el-tree
      class="filter-tree"
      :data="currenTreeData"
      :props="defaultLevTreeProps"
      :check-strictly="true"
      show-checkbox
      :expand-on-click-node="false"
      default-expand-all
      :filter-node-method="filterTreeNode"
      node-key='code'
      @check-change="treeNodeSelectChange"
      ref="levtree">
    </el-tree>
    </el-dialog>
  </div>
</template>

<script>
import pinyin from 'pinyin'
import {
  getClassifylist,
  getTagslist,
  TagsupdateState,
  addTags,
  delTags,
  updateTags,
  fileparse,
  levtree,
  themeTree
} from '../../api/label'
import { tagsSearch } from '../../api/article'
import { baseUrl } from '@/utils/request'
import labelDetails from './labelDetails.vue'
export default {
  name: 'fundProperty',
  components: { labelDetails },
  data() {
    return {
      tagType: 'fund',
      tagDetails: {},
      filterText: '',
      testPass: false,
      treedata: [],
      options: [],
      options1: [],
      listQuery: {
        name: '',
        classCode: '',
        similarWord: '',
        state: '',
        code: '',
        theme: '',
        pageNum: 1,
        pageSize: 20,
        themeCusRelate:'',
        indusCusRelate:''
      },
      treefrom: {
        name: '',
        id: ''
      },
      defaultProps: {
        children: 'list',
        label: 'name',
        id: 'id'
      },
      uploadAction: baseUrl + 'file/upload',
      uploadFileInfo: {
        loading: false,
        status: ''
      },
      downloadInfo: {
        url: baseUrl + 'template/标签模板_基金.xlsx?time=' + Math.random(),
        name: '基金标签上传模板'
      },
      multipleSelection: [],
      dialogFormVisible: false,
      treedialogFormVisible: false,
      listLoading: false,
      tableData: [],
      dataForm: {
        code: '',
        name: '',
        tagCode: '',
        classCode: [],
        s_words: [],
        state: 1,
        themeRelate: [],
        stockRelate: [],
        fundRelate: [],
        firstLevs: [],
        secondLevs: [],
        indusRelate: [],
        customizeFirstLevs: [],
        customizeTheme: []
      },
      showlevTreeFlag: false,
      firstLevTree: [],
      secondLevTree: [],
      themeTree: [],
      currenTreeData: [],
      defaultLevTreeProps: {
        children: 'children',
        label: 'name',
        id: 'code'
      },
      filterlevData: '',
      selectNode: new Map(),
      treeLevtype: '1',
      total: 0,
      rules: {
        name: [
          {
            type: 'string',
            required: true,
            message: '请输入...',
            trigger: 'blur'
          }
        ],
        code: [
          {
            type: 'string',
            required: true,
            message: '请输入...',
            trigger: 'blur'
          }
        ]
      },
      temp: {
        name: 1232
      },
      value: true,
      textMap: {
        update: '编辑',
        create: '新增'
      },
      dialogStatus: '',
      tabledialogStatus: '',
      detailstitle: '',
      dialogdetails: false,
      inputVisible: false,
      inputValue: '',
      fundnameOptions: [],
      fundcodeOptions: [],
      fundthemeOptions: [],
      fundCusThemeOptions:[],
      fundCustIndustryOptions:[],
      loading: false,
      timer: null,
      dialogTitle: '基金行业标签'
    }
  },
  props: {
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    },
    filterlevData(val) {
      this.$refs.levtree.filter(val)
    }
  },
  computed: {},
  methods: {
    debounce(fn, wait) {
      const that = this
      return function() {
        if (that.timer !== null) {
          clearTimeout(that.timer)
        }
        that.timer = setTimeout(fn, wait)
      }
    },
    remoteMethodcode(query) {
      const loadOptions = () => {
        if (query !== '') {
          this.loading = true
          tagsSearch({
            type: 'fund',
            code: query,
            classCode: this.listQuery.classCode
          }).then(res => {
            const list = res.Data.map(i => {
              return {
                ...i, tag_code: i.tagCode
              }
            })
            this.loading = false
            this.fundcodeOptions = list
          })
        } else {
          this.loading = false
          this.fundcodeOptions = []
        }
      }
      this.debounce(loadOptions, 2000)()
    },
    remoteMethodname(query) {
      const loadOptions = () => {
        if (query !== '') {
          this.loading = true
          tagsSearch({
            type: 'fund',
            name: query,
            classCode: this.listQuery.classCode
          }).then(res => {
            const list = res.Data.map(i => {
              return {
                ...i, tag_code: i.tagCode
              }
            })
            this.loading = false
            this.fundnameOptions = list
          })
        } else {
          this.loading = false
          this.fundnameOptions = []
        }
      }
      this.debounce(loadOptions, 2000)()
    },
    remoteMethodtheme(query) {
      const loadOptions = () => {
        if (query !== '') {
          this.loading = true
          tagsSearch({
            type: 'fund',
            theme: query,
            classCode: this.listQuery.classCode
          }).then(res => {
            const list = res.Data.map(i => {
              return {
                ...i, tag_code: i.tagCode
              }
            })
            this.loading = false
            this.fundthemeOptions = list
          })
        } else {
          this.loading = false
          this.fundthemeOptions = []
        }
      }
      this.debounce(loadOptions, 2000)()
    },
    remoteMethodCusTheme(query){
      const loadOptions = () => {
        if (query !== '') {
          this.loading = true
          tagsSearch({
            type: 'theme',
            theme: query,
            classCode: this.listQuery.classCode
          }).then(res => {
            const list = res.Data.map(i => {
              return {
                ...i, tag_code: i.tagCode
              }
            })
            this.loading = false
            this.fundCusThemeOptions = list
          })
        } else {
          this.loading = false
          this.fundCusThemeOptions = []
        }
      }
      this.debounce(loadOptions, 2000)()
    },
    remoteMethodCusIndustry(query){
      const loadOptions = () => {
        if (query !== '') {
          this.loading = true
          tagsSearch({
            type: 'industry',
            industry: query,
            classCode: this.listQuery.classCode
          }).then(res => {
            const list = res.Data.map(i => {
              return {
                ...i, tag_code: i.tagCode
              }
            })
            this.loading = false
            this.fundCustIndustryOptions = list
          })
        } else {
          this.loading = false
          this.fundCustIndustryOptions = []
        }
      }
      this.debounce(loadOptions, 2000)()
    },
    getTree() {
      getClassifylist({
        key: '',
        pageNum: 0,
        pageSize: 0,
        type: 'fund'
      }).then(res => {
        this.treedata = this.cleardel(res.Data)
      })
    },
    getList() {
      getTagslist({
        classCode: this.listQuery.classCode,
        name: this.listQuery.name,
        pageSize: this.listQuery.pageSize,
        pageNum: this.listQuery.pageNum,
        s_words: this.listQuery.similarWord.length > 0 ? [this.listQuery.similarWord] : [],
        state: this.listQuery.state,
        code: this.listQuery.code,
        theme: this.listQuery.theme,
        cusTheme:this.listQuery.themeCusRelate,
        cusIndustry:this.listQuery.indusCusRelate
      }).then(res => {
        this.tableData = res.Data[0].records
        this.total = res.Data[0].total
      })
    },
    resetSearch() {
      this.listQuery.name = ''
      this.listQuery.similarWord = ''
      this.listQuery.state = ''
      this.listQuery.code = ''
      this.listQuery.theme = ''
      this.listQuery.pageNum = 1
      this.getList()
    },
    filterNode(value, data) {
      if (!value) return true
      return (
        data.name.indexOf(value) !== -1 ||
        pinyin(data.name, {
          style: pinyin.STYLE_FIRST_LETTER,
          heteronym: true
        })
          .join('')
          .indexOf(value) !== -1
      )
    },
    cleardel(data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].list.length > 0) {
          this.cleardel(data[i].list)
        } else {
          delete data[i].list
        }
      }
      return data
    },
    getNodeData(data) {
      this.listQuery.classCode = data.code
      this.dataForm.classCode = data.code
      this.getList()
    },
    handleAdd() {
      this.dataForm = {
        code: '',
        name: '',
        tagCode: '',
        classCode: [],
        s_words: [],
        state: 1,
        themeRelate: [],
        stockRelate: [],
        fundRelate: [],
        firstLevs: [],
        secondLevs: [],
        indusRelate: [],
        customizeFirstLevs: [],
        customizeTheme: []
      }
      if (this.listQuery.classCode) {
        this.tabledialogStatus = 'create'
        this.dataForm.classCode = this.listQuery.classCode
        this.dialogFormVisible = true
      } else {
        this.$message.error('请选择一个分类')
      }
    },
    handleStart: function() {
      if (this.multipleSelection.length === 0) return
      TagsupdateState({
        tagCodeList: this.multipleSelection,
        state: 1
      }).then(() => {
        this.getList()
        this.$notify({
          title: '成功',
          message: '启用成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    handleStop() {
      if (this.multipleSelection.length === 0) return
      TagsupdateState({
        tagCodeList: this.multipleSelection,
        state: 0
      }).then(() => {
        this.getList()
        this.$notify({
          title: '成功',
          message: '停用成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    alldelete() {
      if (this.multipleSelection.length === 0) return
      this.$confirm('确定删除这些数据？', '确认信息', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delTags({
            tagCodeList: this.multipleSelection
          }).then(res => {
            if (res.Meta.Code === 0) {
              this.$message({
                type: 'success',
                message: '删除成功'
              })
              this.getList()
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    formatStatus(data) {
      switch (data) {
        case 1:
          return '启用'
        case 0:
          return '停用'
      }
    },
    startParse(response, file, fileList) {
      this.uploadFileInfo.status = '解析中...'
      const params = {
        operateType: 3,
        fileName: response.Data[0].fileName,
        code: this.listQuery.classCode
      }
      fileparse(params).then((res) => {
        this.getList()
        this.$alert('本次导入影响数据' + res.Data[0].successNum + '条', '提示', {
          confirmButtonText: '确定',
          type: 'success'
        })
        const clearFile = () => {
          fileList.splice(fileList.indexOf(file), 1)
        }
        setTimeout(clearFile, 5000)
        this.uploadFileInfo.loading = false
      }).catch(() => {
        this.uploadFileInfo.loading = false
        this.$refs.uploadButton.clearFiles()
      })
    },
    beforeUpload() {
      if (!this.listQuery.classCode) {
        this.$message.error('请选择一个分类')
        return false
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map(i => i.tagCode)
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val
      this.getList()
    },

    filterNode2(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    handleShowEditor(data) {
      this.tabledialogStatus = 'update'
      this.options = data.stockRelate
      this.options1 = data.fundRelate
      const list = JSON.parse(JSON.stringify(data))
      this.dataForm = {
        ...this.dataForm,
        code: list.code,
        name: list.name,
        // theme: list.theme,
        classCode: list.classCode,
        tagCode: list.tagCode,
        s_words: list.simWords,
        state: list.state,
        stockRelate: list.stockRelate.map(i => i.tagCode),
        fundRelate: list.fundRelate.map(i => i.tagCode)
      }

      if (list.themeCusRelate) {
        this.dataForm.themeRelate = list.themeRelate
      }

      this.dataForm.customizeTheme = list.themeCusRelate.map(val => {
        return [val.code, val.name]
      })

      this.dataForm.customizeFirstLevs = list.indusCusRelate.map(val => {
        return [val.code, val.name + '(' + (val.level === 1 ? '一级' : '二级') + ')']
      })

      this.dataForm.indusRelate = list.indusRelate
      this.dialogFormVisible = true
    },
    closedig() {
      this.dataForm = {
        code: '',
        name: '',
        theme: '',
        classCode: this.listQuery.classCode,
        s_words: [],
        state: 1,
        stockRelate: [],
        fundRelate: [],
        customizeFirstLevs: [],
        customizeTheme: []
      }
      this.dialogFormVisible = false
    },
    handleTableDelete(data) {
      this.$confirm('确定删除本条数据？', '确认信息', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delTags({
            tag_code: data.tagCode
          }).then(res => {
            if (res.Meta.Code === 0) {
              this.$message({
                type: 'success',
                message: '删除成功'
              })
              this.getList()
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    handleDet(data) {
      this.dialogdetails = true
      this.detailstitle = data.name
      this.tagDetails = data
    },
    remoteMethod(query) {
      const loadOptions = () => {
        if (query !== '' && !this.loading) {
          this.loading = true
          tagsSearch({
            key: query,
            type: 'stock'
          }).then(res => {
            this.loading = false
            this.options = res.Data
          })
        } else {
          this.options = []
        }
      }
      this.debounce(loadOptions, 2000)()
    },
    createData() {
      console.log(this.dataForm)
      this.$refs['dataForm'].validate((val) => {
        if (val) {
          addTags('fund', this.dataForm).then((res) => {
            if (res.Meta.Code === 0) {
              this.getList()
              this.$message.success('添加成功')
            } else {
              this.$message.error(res.Meta.Message)
            }
            this.closedig()
          })
        } else {
          return false
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((val) => {
        if (val) {
          const saveFormData = { ...this.dataForm }
          delete saveFormData.themeRelate

          saveFormData.indusCusRelate = saveFormData.customizeFirstLevs.map(val => {
            return val[0]
          })

          saveFormData.themeCusRelate = saveFormData.customizeTheme.map(val => {
            return val[0]
          })

          updateTags('fund', saveFormData).then(res => {
            if (res.Meta.Code === 0) {
              this.$message.success('编辑成功')
              this.getList()
            } else {
              this.$message.success('编辑失败')
            }
            this.closedig()
          })
        } else {
          return false
        }
      })
    },
    handleClose1(tag) {
      this.dataForm.s_words.splice(this.dataForm.s_words.indexOf(tag), 1)
    },
    showInput() {
      this.inputVisible = true
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.dataForm.s_words.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    showTreeDiag(type) {
      this.treeLevtype = type
      this.showlevTreeFlag = true
      this.filterlevData = ''

      let selectTreeKey = []
      if (type === '1') {
        this.dialogTitle = '基金行业标签'
        this.currenTreeData = [...this.secondLevTree]
        selectTreeKey = this.dataForm.customizeFirstLevs.length > 0 && this.dataForm.customizeFirstLevs.map(val => {
          return val[0]
        })
      } else {
        this.dialogTitle = '基金主题标签'
        this.currenTreeData = [...this.themeTree]
        selectTreeKey = this.dataForm.customizeTheme.length > 0 && this.dataForm.customizeTheme.map(val => {
          return val[0]
        })
      }
      if (selectTreeKey&&selectTreeKey.length > 0) {
        this.$nextTick(() => {
          this.$refs.levtree.setCheckedKeys(selectTreeKey)
        })
      }else{
        this.$nextTick(() => {
          this.$refs.levtree.setCheckedKeys([])
        })
      }
    },
    filterTreeNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    treeNodeSelectChange() {
      const keys = this.$refs.levtree.getCheckedKeys()
      this.selectNode = new Map()
      this.recursionDataFromKey(keys, this.currenTreeData)
      const entities = this.selectNode.entries()
      if (this.treeLevtype === '1') {
        this.dataForm.customizeFirstLevs = [...entities]
      } else {
        this.dataForm.customizeTheme = [...entities]
      }
    },

    recursionDataFromKey(keys, dataList) {
      dataList = Array.isArray(dataList) ? dataList : []
      for (let index = 0; index < dataList.length; index++) {
        const element = dataList[index]
        if (element.children && element.children.length > 0) {
          this.recursionDataFromKey(keys, element.children)
        }
        if (keys.includes(element.code)) {
          if(this.treeLevtype==='1'){
            this.selectNode.set(element.code, element.name+'('+(element.children&&element.children.length>0?'一级':'二级')+')')
          }else{
            this.selectNode.set(element.code, element.name)
          }
        }
      }
    },
    // 获取基金一级行业树结构
    getFundLev1tree() {
      return new Promise((resolve, reject) => {
        levtree({ level: 1 }).then(res => {
          const list = Array.isArray(res.Data) ? res.Data : []
          this.firstLevTree = list
          resolve()
        })
      })
    },
    // 去获取基金行业树结构
    getFundLev2tree() {
      return new Promise((resolve, reject) => {
        levtree({ level: 2 }).then(res => {
          const list = Array.isArray(res.Data) ? res.Data : []
          this.secondLevTree = list
          resolve()
        })
      })
    },
    // 获取自定义基金主题
    getFundTheme() {
      themeTree({}).then(res => {
        const list = Array.isArray(res.Data) ? res.Data : []
        this.themeTree = list
      })
    },
    handleThemeClose(tag){
      let list = [...this.dataForm.customizeTheme]
      for (let i = 0; i < list.length; i++) {
        if(list[i][0]==tag[0]){
          list.splice(i,1)
          break
        }
      }
      this.dataForm.customizeTheme = list

      // this.dataForm.customizeTheme.splice(this.dataForm.customizeTheme.indexOf(tag),1)
    },
    handleIndustryClose(tag){

      let list = [...this.dataForm.customizeFirstLevs]
      for (let i = 0; i < list.length; i++) {
        let  item = list[i];
        if(item[0]==tag[0]){
          list.splice(i,1)
          break
        }
      }
      this.dataForm.customizeFirstLevs = list

    }
  },
  mounted() {
    this.getTree()
    setTimeout(() => {
      this.getFundTheme()
    }, 2 * 1000)
  },
  created() {
    this.getFundLev2tree()
  },
  destroyed() {}
}
</script>

<style lang="stylus" scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}


</style>
<style>
.fundProperty .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content{
  background-color:#409eff;
  color:#ffffff;
}
.dialog-tree .el-dialog__body{
  max-height:250px;
  overflow-y:auto;
}
</style>
